import com.stein.utils.EsClient;
import org.elasticsearch.action.admin.indices.alias.get.GetAliasesRequest;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.GetAliasesResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.json.JsonXContent;
import org.junit.Test;

public class ESTest01 {

//    高级客户端
    RestHighLevelClient client = EsClient.getClient();

    private String index = "super";

    /**
     *
     * 创建索引
     */
    @Test
    public  void test01() throws Exception{

        //创建分片
        Settings.Builder settings = Settings.builder()
                .put("number_of_shards", 5)
                .put("number_of_replicas", 1);

        //创建索引结构
        XContentBuilder mapping = JsonXContent.contentBuilder()
                .startObject()
                .startObject("properties")
                        .startObject("name")
                        .field("type", "text")
                        .field("analyzer", "ik_max_word")
                        .field("index", true)
                        .field("store", false)
                    .endObject()
                    .startObject("birthday")
                        .field("type", "date")
                        .field("format", "yyyy-MM-dd")
                    .endObject()
                    .startObject("desc")
                        .field("type", "text")
                        .field("analyzer", "ik_max_word")
                    .endObject()
                .endObject()
                .endObject();
        //将分片和索引封装成一个request对象
        CreateIndexRequest indexRequest = new CreateIndexRequest(index).settings(settings).mapping(mapping);

        //发送创建请求
        CreateIndexResponse response = client.indices().create(indexRequest, RequestOptions.DEFAULT);

        System.out.println("创建的结果是"+response);
    }

    /**
     *
     * 查看目标索引是否存在
     * @throws Exception
     */

    @Test
    public void test02() throws Exception{
        GetIndexRequest request = new GetIndexRequest(index);


        boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);

        System.out.println("super 索引是否存在："+exists);
    }


    @Test
    public void deleteIndex() throws Exception{
        DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(index);
        AcknowledgedResponse response = client.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);

        System.out.println(index+"索引是否删除成功："+response.isAcknowledged());
    }
}
